package com.mutouren.web.org;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.mutouren.common.entity.PageInfo;
import com.mutouren.common.entity.ValidState;
import com.mutouren.common.utils.StringUtils;
import com.mutouren.common.web.BootStrapPage;
import com.mutouren.common.web.ParsePageInfo;
import com.mutouren.modules.org.model.Organization;
import com.mutouren.modules.org.model.OrganizationPerson;
import com.mutouren.modules.org.model.Person;
import com.mutouren.modules.org.service.OrganizationService;
import com.mutouren.modules.org.service.PersonService;
import com.mutouren.web.WebUtils;

@Controller
@RequestMapping(value="/org/person")
public class PersonAction {
	
	@Resource
	private PersonService personService;
	
	@Resource
	private OrganizationService organizationService;	
	
//	@InitBinder
//	public void initBinder(WebDataBinder binder) {  
//		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");  
//		dateFormat.setLenient(false);  
//		binder.registerCustomEditor(Date.class, new DateEditor(dateFormat, true));
//	}
	
//	@ExceptionHandler(Throwable.class)  
//	@ResponseStatus(value = HttpStatus.BAD_REQUEST)  
//	public void handleInvalidRequestError(HttpServletResponse response, TypeMismatchException ex) {  
//		for(ObjectError objError : error.getAllErrors()) {
//			if (objError instanceof FieldError) {
//				FieldError fe = (FieldError)objError;
//				sb.append(String.format("className:%s, fieldName:%s", fe.getObjectName(), 
//						fe.getField()));
//			}
//		}
//	}	
	
	@RequestMapping(value="/manage.action")
	public String manage(HttpServletRequest request) {
		PageInfo pageInfo = ParsePageInfo.parse(request);
		List<Person> listPerson = new ArrayList<Person>();
		request.setAttribute("listPerson", listPerson);
		
		List<Organization> listOrganization = organizationService.getChildren(Organization.ROOT_ID, true, true, false, ValidState.Normal);		
		request.setAttribute("listOrganization", OrgUtils.convertOrganizationToJSON(listOrganization));			
		request.setAttribute("mtrPage", BootStrapPage.buildHtmlPage(pageInfo));	
		
		return "modules/org/personList";
	}

	@RequestMapping(value="/add.action")
	public String add(@ModelAttribute("person") Person person, 
			HttpServletRequest request, HttpServletResponse response) {

		request.setAttribute("actionName", WebUtils.getActionName(request));
		if (!WebUtils.isPost(request)) {
			Organization org = this.organizationService.get(person.getOrgId());
			person.setOrgPath(org.getChineseAllPath());
			return "modules/org/personForm";
		}
		
		List<String> errors = new ArrayList<String>();
		if(this.validate(request, person, errors)) {
			return WebUtils.failDialog(response, WebUtils.getErrorMessage(errors));
		}

		this.personService.add(person);
		return WebUtils.successDialog(response);
	}

	@RequestMapping(value="/modify.action")
	public String modify(@ModelAttribute("person") Person person,
			ModelMap map,
			HttpServletRequest request, HttpServletResponse response) {

		request.setAttribute("actionName", WebUtils.getActionName(request));
		if (!WebUtils.isPost(request)) {
			person = personService.get(person.getPersonId());
			map.addAttribute("person", person);
			return "modules/org/personForm";
		}

		List<String> errors = new ArrayList<String>();
		if(this.validate(request, person, errors)) {
			return WebUtils.failDialog(response, WebUtils.getErrorMessage(errors));
		}	

		int result = personService.modify(person);
		if (result == 1) {
			return WebUtils.successDialog(response);
		} else {
			return WebUtils.failDialog(response, "编辑数据不存在");
		}
	}
	
	@RequestMapping(value="/changeState.action")
	public void changeState(@RequestParam(value="personId") int personId,
			@RequestParam(value="orgId") int orgId, String validState, HttpServletResponse response) throws IOException {
		
		OrganizationPerson op = new OrganizationPerson(orgId, personId);
		op.setValidState(ValidState.valueOf(validState));
		
		if (personService.setState(op) >= 1) {
			response.getWriter().write("success");
		} else {
			response.getWriter().write("fail");
		}
	}

	@RequestMapping(value="/joinMember.action")
	public void joinMember(@RequestParam(value="personId") int personId, 
			@RequestParam(value="orgId") int orgId,
			HttpServletResponse response) throws IOException {
			
		personService.addToOrg(orgId, personId);
		
		response.getWriter().write("success");
	}	

	@RequestMapping(value="/changeOrg.action")
	public void changeOrg(@RequestParam(value="personId") int personId, 
			@RequestParam(value="oldOrgId") int oldOrgId,
			@RequestParam(value="newOrgId") int newOrgId,
			HttpServletResponse response) throws IOException {
		
		personService.changeOrg(personId, oldOrgId, newOrgId);
		response.getWriter().write("success");
	}

	@RequestMapping(value="/resetPassword.action")
	public void resetPassword(@RequestParam(value="personId") int personId, 
			HttpServletResponse response) throws IOException{
		
		personService.resetPassword(personId);
		response.getWriter().write("success");
	}		

	@RequestMapping(value="/grid.action")
	public String grid(@RequestParam(value="orgId") int orgId,
			@RequestParam(value="isDisplayChild") boolean isDisplayChild,
			@RequestParam(value="isOnlyMainPosition") boolean isOnlyMainPosition,
			@RequestParam(value="searchName") String searchName,
			HttpServletRequest request) throws UnsupportedEncodingException {
		PageInfo pageInfo = ParsePageInfo.parse(request);
		//searchName = new String(request.getParameter("searchName").getBytes("iso8859-1"),"utf-8");

		List<Person> listPerson = personService.selectByOrgId(orgId, isOnlyMainPosition, isDisplayChild, searchName, pageInfo);

		request.setAttribute("listPerson", listPerson);	
		request.setAttribute("mtrPage", BootStrapPage.buildHtmlPage(pageInfo));	
		
		return "modules/org/personGrid";
	}
	
	@RequestMapping(value="/setMainPosition.action")
	public void setMainPosition(@RequestParam(value="personId") int personId,
			@RequestParam(value="orgId") int orgId,
			HttpServletResponse response) throws IOException {
		
		personService.setMainPosition(personId, orgId);
		response.getWriter().write("success");
	}
	
	@RequestMapping(value="/selectPosition.action")
	public String selectPosition(@RequestParam(value="personId") int personId,
			HttpServletRequest request) {
		
		List<Organization> listOrganization = personService.selectPosition(personId);		
		request.setAttribute("listOrganization", listOrganization);
			
		return "modules/org/positionSelect";
	}

	public boolean validate(HttpServletRequest request, Object model, List<String> errors ) {
		String actionName = (String) request.getAttribute("actionName");

		// person
		if (actionName.equals("add") || actionName.equals("modify")) {
			Person person = (Person) model;
			
			if (StringUtils.isBlank(person.getLoginName())) {
				errors.add("登录名: 不能为空");
			}

			if (StringUtils.isBlank(person.getName())) {
				errors.add("姓名: 不能为空");
			}
			
			if (StringUtils.isBlank(person.getEmail())) {
				errors.add("邮箱: 不能为空");
			}			
			
			if (person.getBirthday() == null) {
				String birthday = request.getParameter("birthday");
				if (StringUtils.isBlank(birthday)) {
					//organization.setSequence(0);
				} else {
					errors.add("生日: 格式有误，例如: 2017-01-01");
				}
			}
						
			person.setEmail(StringUtils.isBlank(person.getEmail()) ? null : person.getEmail().trim());
			person.setMobile(StringUtils.isBlank(person.getMobile()) ? null : person.getMobile().trim());		
		}

		return errors.size() > 0;
	}	

}
